package com.wanjia.bpsapi.crontab;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanjia.bpsapi.pojo.entity.WjSupplier;
import com.wanjia.bpsapi.properties.TimedTaskProperties;
import com.wanjia.bpsapi.service.IWjSupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class TimedTaskBase {
    @Autowired
    TimedTaskProperties timedTaskProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    IWjSupplierService wjSupplierService;

    public void run(){
        log.info("获取基地信息定时任务执行中...");
        String BaseUrl = timedTaskProperties.getBaseUrl()+"?page=0&limit=9999999";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Token", timedTaskProperties.getToken());
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response= restTemplate.exchange(BaseUrl, HttpMethod.GET, entity,String.class);
        String body = response.getBody();
        JSONObject jb = JSONObject.parseObject(body);
        JSONArray data = jb.getJSONObject("data").getJSONArray("data");
        wjSupplierService.remove(new QueryWrapper<>());
        for (int i = 0; i < data.size(); i++) {
            JSONObject object = data.getJSONObject(i);
            WjSupplier wjSupplier = JSON.parseObject(String.valueOf(object), WjSupplier.class);
            wjSupplierService.addBase(wjSupplier);
        }
    }
}
